import type { TableProps, ColumnType } from '../types'

import { ref, computed, watchEffect } from 'vue'
import { cloneDeep } from 'lodash-es'

const useColumns = (props: TableProps) => {
  const columnsRef = ref<ColumnType[]>([])
  const flattenedColumnsRef = ref<ColumnType[]>([])
  const columnsWidthRef = ref<Record<string, number>>({})

  const getColumns = computed(() => columnsRef.value)

  const getLeftColumns = computed(() => getColumns.value.filter((col) => col.fixed === 'left'))

  const getRightColumns = computed(() => getColumns.value.filter((col) => col.fixed === 'right'))

  const getFlattenedColumns = computed(() => flattenedColumnsRef.value)

  watchEffect(() => {
    columnsRef.value = cloneDeep(props.columns)
    for (const col of columnsRef.value) {
      flattenColumn(col)
    }
  })

  function flattenColumn(col: ColumnType) {
    let flag = false
    const inner = (columns: ColumnType[]) => {
      for (const column of columns) {
        column.resizable = false
        if (column.children && column.children.length > 0) {
          inner(column.children)
        } else {
          column.flat = col.field
          if (!flag) {
            column.flatRender = true
            flag = true
          } else {
            column.flatRender = false
          }
          flattenedColumnsRef.value.push(column)
        }
      }
    }
    if (col.children && col.children.length > 0) {
      col.resizable = false
      inner(col.children)
    } else {
      flattenedColumnsRef.value.push(col)
    }
  }

  return {
    columnsWidthRef,
    getColumns,
    getLeftColumns,
    getRightColumns,
    getFlattenedColumns
  }
}

export default useColumns
